<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 提示栏 -->
      <el-alert
        title="警告提示的文案"
        type="warning"
        center
        show-icon
      ></el-alert>
      <!-- 步骤条 -->
      <el-steps align-center :active="activeIndex - 0"
      finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="changeTabsHandle"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
              v-model="addForm.goods_cat"
              :options="cateList"
              :props="cascaderOpt"
              clearable
              @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox  border :label="item1" v-for="(item1,index) in item.attr_vals" :key="index">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="(item,index) in onlyData" :key="index">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片列表缩略图 -->
            <el-upload
              action="http://8.131.91.46:7000/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headerObj"
              :on-success="handleSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button @click="publish" type="warning">发布商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog
      title="显示图片"
      :visible.sync="previewDialog"
      width="50%"
      @close="removeImg">
      <img :src="previewImg" class="previewImg" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'addGoods',
  data () {
    return {
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [], // 商品分类
        pics: [],
        goods_introduce: '',
        attrs: []

      }, // 商品数据
      // 校验规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]
      },
      cateList: [], // 商品分类参数列表
      cascaderOpt: {
        expandTrigger: 'hover', // 次级菜单的展开方式
        value: 'cat_id', // 索引
        label: 'cat_name', // 内容
        children: 'children'
      },
      manyData: [], // 动态参数数据
      onlyData: [], // 静态参数数据
      headerObj: {
        Authorization: sessionStorage.getItem('token')
      },
      previewDialog: false,
      previewImg: ''
    }
  },
  created () {
    // 获取商品分类
    this.getGoodsCate()
  },
  methods: {
    // 获取商品分类
    async getGoodsCate () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.$message.success(res.meta.msg)
      this.cateList = res.data
    },
    handleChange () {
      const cateLength = this.addForm.goods_cat.length
      if (cateLength !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 阻止跳转
    beforeLeave (activeName, oldActivename) {
      const cateLength = this.addForm.goods_cat.length
      if (cateLength !== 3 && oldActivename === '0') {
        this.$message.error('请选择分类')
        return false
      }
    },
    // 切换Tabs事件
    async changeTabsHandle () {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.getCateId}/attributes`, {
            params: { sel: 'many' }
          })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        // 字符串转换成数组
        res.data.forEach(item => {
          item.attr_vals =
          item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        console.log(res.data)
        this.$message.success(res.meta.msg)
        this.manyData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.getCateId}/attributes`, {
            params: { sel: 'many' }
          })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.onlyData = res.data
      }
    },
    // 图片预览
    handlePreview (file) {
      console.log(file)
      const imgUrl = file.response.data.url
      this.previewImg = imgUrl
      this.previewDialog = true
    },
    // 清除数据
    removeImg () {
      this.previewImg = ''
    },
    // 移除上传数据
    handleRemove (file) {
      console.log(file)
      const { pics } = this.addForm
      const removeImg = file.response.data.tmp_path
      const index = pics.findIndex(item => item.pic === removeImg)
      pics.splice(index, 1)
    },
    // 上传成功
    handleSuccess (response) {
      if (response.meta.status !== 200) {
        return this.$message.error('上传失败！')
      }
      const imgObj = {
        img: response.data.tmp_path
      }
      this.addForm.pics.push(imgObj)
    },
    // 发布商品
    publish () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入商品参数')
        const { goods_cat: goodsCat } = this.addForm
        const newGoodsCate = goodsCat.join(',')
        this.addForm.goods_cat = newGoodsCate
        this.addForm.pics = this.addForm.pics.toString()

        this.manyData.forEach(item => {
          const newData = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newData)
        })
        this.onlyData.forEach(item => {
          const newData = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newData)
        })
        const { data: res } = await this.$http.post('goods', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
      })
    }
  },
  computed: {
    // 获取ID
    getCateId () {
      const { goods_cat: goodCate } = this.addForm
      if (goodCate.length !== 3) {
        return null
      }
      const length = goodCate.length
      return goodCate[length - 1]
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 20px 0;
  // /deep/深度选择器
  // 默认情况下，样式不能作用到子组件
  // 但我们必须对子组件样式进行调整
  // 这时候可以给类名前加 /deep/
  // 如果/deep/报错，可以使用 >>> 或者 ::v-deep 来替换

  /deep/.el-step__title {
    font-size: 14px;
  }
}
.el-tabs {
  margin-top: 50px;
  /deep/.el-tabs__item{
    height: 80px;
  }
  /deep/.el-form-item{
    margin: 0 20px;
      /deep/.el-checkbox{
        margin-right: 10px;
  }
  }

}
.previewImg{
  width: 100%;
  height: 100%;
}
</style>
